package kercar.robot;

import kercar.manager.CompassManager;
import kercar.manager.GPSManager;
import kercar.robot.serialcom.SerialRead;

public class ArduinoRobot implements Robot {

	/************************************************************************* BLOCK
	 * ATTRIBUTES
	 *******************************************************************************/
	
	private final static String FORWARD = "z";
	private final static String BACKWARD = "s";
	private final static String TURNRIGHT = "d";
	private final static String TURNLEFT = "q";
	private final static String STOP = "e";
	
	private TListener _tlistener;
	private SerialRead _serialRead;

	private GPSManager _gpsManager;
	private CompassManager _compManager;
	
	/************************************************************************* BLOCK
	 * CONSTRUCTOR
	 *******************************************************************************/
	
	public ArduinoRobot() {
		_tlistener = new TListener();
	}

	/************************************************************************* BLOCK
	 * PUBLIC METHODS
	 *******************************************************************************/
	
	public void startListener() {
		_tlistener.start();
	}
	
	@Override
	public void moveForward(double speed) {
		_serialRead.write(FORWARD);
	}

	@Override
	public void moveBackward(double speed) {
		_serialRead.write(BACKWARD);
	}

	public void turn(int angle) {
		if (angle > 0) {
			_serialRead.write(TURNRIGHT);
		}
		else {
			_serialRead.write(TURNLEFT);
		}
	}

	@Override
	public void stopMoving() {
		_serialRead.write(STOP);
	}
	
	/************************************************************************* BLOCK
	 * 		GETTERS & SETTERS
	 *******************************************************************************/
	
	public void setGPSManager(GPSManager gpsManager) {
		_gpsManager = gpsManager;
	}
	
	public void setCompassManager(CompassManager compManager) {
		_compManager = compManager;
	}
	
	/************************************************************************* BLOCK
	 * PRIVATE CLASSES
	 *******************************************************************************/
	
	private class TListener extends Thread {
		public void run() {
			_serialRead = new SerialRead();
			_serialRead.setGPSManager(_gpsManager);
			_serialRead.setCompassManager(_compManager);
			
			_serialRead.initialize();
			
			while (true) {
				// keep alive
//				Thread.yield();
			}
		}
	}

}
